using UnityEngine;
using System.Collections;

public class Personagem : MonoBehaviour 
{
	private int id = 1;
	
    private float width = 4.0f;
    private float height = 4.0f;
	
	private Vector2 screen;
	private int force;
	
	void Start () 
	{
		this.gameObject.AddComponent("MeshRenderer");
		this.gameObject.AddComponent("MeshFilter");
		this.gameObject.AddComponent("BoxCollider");
		
		this.screen.y = GameObject.Find("Main Camera").GetComponent<Camera>().orthographicSize;
		this.screen.x = this.screen.y * GameObject.Find("Main Camera").GetComponent<Camera>().aspect;
		
        this.gameObject.GetComponent<BoxCollider>().size = new Vector3(2 * this.width, 2 * this.height, 0.1f);
		
        Mesh mesh = Quad.Create(this.width, this.height);
		
		this.gameObject.GetComponent<MeshFilter>().mesh = mesh;
		this.gameObject.GetComponent<MeshRenderer>().material = AtlasJogo.globalMaterial;
		
		this.transform.position = new Vector3(0, -2, 0);
		
		this.StartCoroutine(Caindo());
	}
	
	void Update () 
    {
		this.gameObject.GetComponent<MeshFilter>().mesh.uv = new Vector2[]
		{
			new Vector2(AtlasJogo.rects[id].xMin, AtlasJogo.rects[id].yMax),
			new Vector2(AtlasJogo.rects[id].xMax, AtlasJogo.rects[id].yMax),
			new Vector2(AtlasJogo.rects[id].xMax, AtlasJogo.rects[id].yMin),
			new Vector2(AtlasJogo.rects[id].xMin, AtlasJogo.rects[id].yMin)
		};
		
		if(this.force < 0)
		{
			this.force = 0;	
		}
		
		if(this.force > 150)
		{
			this.force = 150;
			StopAllCoroutines();
		}
		
		if(this.force <= 50)
		{
			this.id = 2;
		}
		
		if(this.force > 50 && this.force <= 100)
		{
			this.id = 3;
		}
		
		if(this.force > 100 && this.force <= 150)
		{
			this.id = 4;	
		}
	}
	
	void FixedUpdate ()
	{
		if(Input.GetKeyDown(KeyCode.Space) && GameObject.Find("Relogio").GetComponent<Cronometro>().start)
		{
			this.force += 6;	
		}
	}
	
	IEnumerator Caindo()
	{
		yield return new WaitForSeconds(0.2f);
		
		this.force -= 5;
		this.StartCoroutine(Caindo());
	}
}
